package teach.aistar.controller;


import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import teach.aistar.model.entity.User;
import teach.aistar.model.vo.Result;
import teach.aistar.service.IUserService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginIndexController {




    @Autowired
    private  IUserService iUserService;
    @PostMapping("/update")
    @ResponseBody
    public Result update(@Validated User user, BindingResult bindingResult, HttpServletRequest request, HttpSession s)
    {

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        Map<String,String> map = new HashMap<>();

        if(fieldErrors.size()>0&&fieldErrors!=null)
        {
            for (FieldError fieldError: fieldErrors) {

                System.out.println(fieldError.getField());
                System.out.println(fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());

            }

           return new Result("400","格式错误，请重新修改",map);


        } else {



            String uname = request.getParameter("uname");
            String pwd = request.getParameter("pwd");
            Integer uId = (Integer) s.getAttribute("uId");
            System.out.println(uname);
            System.out.println(pwd);

            User byUsername = iUserService.getByUsername(uname);
            if(byUsername==null) {

                int update = iUserService.update(uname, pwd, uId);
                System.out.println("update更新是否成功" + update);
                return new Result("200", "修改成功",null);
            }

            else

                return  new Result("201","用户名已经存在，请重新修改",null);



        }

    }

}
